﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace Encloser.Json
{
    public class JsonArray : JsonItem, ICollection<JsonItem>, IEnumerable<JsonItem>, ICollection, IEnumerable
    {
        private readonly List<JsonItem> values = new List<JsonItem>();
        internal override object Value { get => values; }
        public JsonArray() : base(JsonType.Array) {}
        public JsonItem this[int index]
        {
            get => index < 0 || index >= values.Count ? null : values[index];
            set { if (index >= 0 && index < values.Count) values[index] = value; } 
        }
        public int Count => values.Count;
        bool ICollection<JsonItem>.IsReadOnly => false;
        object ICollection.SyncRoot => this;
        bool ICollection.IsSynchronized => false;
        public void Add(JsonItem item) => values.Add(item);
        public void Add(object item) 
        {
            if (item == null) values.Add(null);
            else if (item is JsonItem) values.Add(item as JsonItem);
            else JsonParser.ToJsonItem(item).Try(val => values.Add(val));
        }
        public void Clear() => values.Clear(); 
        public bool Contains(JsonItem item) => values.Contains(item); 
        public void CopyTo(JsonItem[] array, int arrayIndex) => values.CopyTo(array, arrayIndex); 
        public void CopyTo(Array array, int index) => (values as ICollection).CopyTo(array, index); 
        public IEnumerator<JsonItem> GetEnumerator() => values.GetEnumerator(); 
        public bool Remove(JsonItem item) => values.Remove(item); 
        IEnumerator IEnumerable.GetEnumerator() => values.GetEnumerator();
    }
}
